package com.ideal.frame.sys.controller;

import cn.hutool.core.lang.Assert;
import com.ideal.frame.common.dto.ResponseModel;
import com.ideal.frame.common.enumerate.ResponseCode;
import com.ideal.frame.sys.dto.LoginDto;
import com.ideal.frame.sys.dto.UserDto;
import com.ideal.frame.sys.dto.UserToken;
import com.ideal.frame.sys.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: jin
 * @CreateTime: 2019-11-04 17:55
 * @Description: 登录控制层
 */
@Slf4j
@RestController
@RequestMapping("/sys")
@Api(tags = "用户登录接口")
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;
    @Autowired
    private AuthService authService;

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录", notes = "登录成功返回token")
    public ResponseModel<UserToken> login(@RequestBody LoginDto user){
        UserToken userToken = authService.login(user.getUsername(), user.getPassword());
        return ResponseModel.success(userToken);
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @ApiOperation(value = "登出", httpMethod = "POST", produces = "application/json", response = ResponseModel.class)
    @PostMapping("/logout")
    public ResponseModel logout(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        Assert.notNull(token, ResponseCode.UNAUTHORIZED.getMessage());
        authService.logout(token);
        return ResponseModel.success("登出成功");
    }

    @GetMapping(value = "/user")
    @ApiOperation(value = "根据token获取用户信息", notes = "根据token获取用户信息")
    public ResponseModel<UserDto> getUser(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        Assert.notNull(token, ResponseCode.UNAUTHORIZED.getMessage());
        UserDto userDto = authService.getUserByToken(token);
        return ResponseModel.success(userDto);
    }

//    @GetMapping(value = "refresh")
//    @ApiOperation(value = "刷新token")
//    public ResultJson refreshAndGetAuthenticationToken(
//            HttpServletRequest request){
//        String token = request.getHeader(tokenHeader);
//        ResponseUserToken response = authService.refresh(token);
//        if(response == null) {
//            return ResultJson.failure(ResultCode.BAD_REQUEST, "token无效");
//        } else {
//            return ResultJson.ok(response);
//        }
//    }
}
